package com.ogawa.chair7808.ui.activity

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.base.Constant.CommmandNum
import com.ogawa.base.Constant.Constant.LIVE_EVENT_BUS_KEY_END_TIME
import com.ogawa.base.Constant.MqttConstant.EVENT_BUS_KEY_RECEIVE_MESSAGE
import com.ogawa.base.Constant.MqttConstant.LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE
import com.ogawa.base.mqtt.MqttConnectListener
import com.ogawa.base.mqtt.MqttManager
import com.ogawa.base.mqtt.MqttReceiveListener
import com.ogawa.base.mqtt.MqttSendMsgCallback
import com.ogawa.base.utils.ActivityManager
import com.ogawa.base.utils.StringUtils
import com.ogawa.chair7808.bean.Massage7808Armchair
import com.ogawa.chair7808.bean.TempDevice7808StateBean
import com.ogawa.chair7808.manager.DataManager
import com.ogawa.chair7808.manager.DataManager.Companion.inst
import com.ogawa.chair7808.manager.TimeBean
import com.ogawa.chair7808.ui.dialog.AntiPinchDialog
import com.ogawa.chair7808.utils.Activity7808Utils
import org.eclipse.paho.client.mqttv3.IMqttActionListener
import org.eclipse.paho.client.mqttv3.IMqttToken
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * Activity 的基类封装
 * Created by HourGlassRemember on 2018/8/6.
 */
abstract class BaseMqtt7808Activity : BaseActivity(), MqttConnectListener, MqttReceiveListener {

    private var isFinishShow = false
    override fun initView(layoutId: Int) {
        super.initView(layoutId)
        LiveEventBus.get(LIVE_EVENT_BUS_KEY_END_TIME, TimeBean::class.java).observe(this, {
            publish(CommmandNum.FINISH, "4")
            if (!isFinishShow) {
                isFinishShow = true
                showFinishDialog(this, "-1", {
                    isFinishShow = false;
                    cancleFinishDialog()
                })
            }
        })

        LiveEventBus.get(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE).observe(this, {
            try {
                changeViewByMqttMessage()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            try {
                changeActivity()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        })

    }

    /**
     * 界面跳转相关
     */
    private fun changeActivity() {
        val topActivity = ActivityManager.getInstance().currentActivity()
        inst.getDevice7808StateBean()?.let {
            //防夹 弹窗判断
            it.antiPinchCheck?.let {
                if (it != "0") {
                    if (!AntiPinchDialog.isShowAntiPinchDialog) {
                        AntiPinchDialog.isShowAntiPinchDialog = true
                        val antiPinchDialog = AntiPinchDialog()
                        antiPinchDialog.setBaseActivity(this)
                        antiPinchDialog.show(supportFragmentManager, "AntiPinchDialog")
                    }
                }
            }

            //肩部检测判断
            it.shoulderDetectCheck?.let {
                if (it == "3" || it == "6") {
                    if (topActivity !is ScanShoulderActivity7808 || topActivity !is ShouldersAdjustmentActivity7808) {
                        Activity7808Utils.startScanShoulderActivity(this)
                        return
                    }
                }
            }

            it.autoProgram?.let {
                var value = 0
                if (it != null) {
                    value = StringUtils.getValue(it)
                }
                if (!DataManager.inst.isHandOutMessageActivity
                        && value > 0
                        && topActivity !is AdvancedMassageActivity7808
                ) {
                    Activity7808Utils.startAdvancedMassageActivity(this)
                }
            }


        }
    }


    abstract fun changeViewByMqttMessage()


    override fun onReceiveMqttMsg(topic: String?, message: MqttMessage?) {
        if (topic == null || message == null) {
            return
        }
        val msg = String(message.payload)
        LogUtils.e("$TAG 处理消息 ${topic} :   ${msg}")
        try {
            if (topic.contains("up")) { //设备状态的消息
                if (!msg.contains("fault") && !msg.contains("elecTime") && !msg.contains("heartbeat")) {
                    Massage7808Armchair.getInstance().tempDeviceStatusBean = GsonUtils.fromJson(msg, TempDevice7808StateBean::class.java)
                    Massage7808Armchair.getInstance().tempDeviceStatusBean?.functions?.let {
                        try {
                            val modelValue = it.autoProgram.modelValue
                            if (StringUtils.getValue(modelValue) > 0) {
                                if (DataManager.inst.lastAutoProgram != StringUtils.getValue(modelValue)) {
                                    DataManager.inst.isHandOutMessageActivity = false
                                }
                            }
                            DataManager.inst.lastAutoProgram =StringUtils.getValue(modelValue)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                        DataManager.inst.analysisDeviceStatusBean(it)
                    }

                } else if (msg.contains("fault")) { //设备故障码
                    val functions: String = JSONObject(msg).getString("functions")
                    val fault = JSONObject(functions).getString("fault")
                    val faultResult = JSONObject(fault).getString("modelValue")
                    Massage7808Armchair.getInstance().fault = faultResult
                }
            } else if (topic.contains("back")) { //发送消息的回复
                val cmdResult: String = JSONObject(msg).getString("cmdResult")
                var sendState = 0
                when (cmdResult) {
                    "success" -> sendState = MqttSendMsgCallback.SUCCESS
                    "fail" -> sendState = MqttSendMsgCallback.FAIL
                    "timeout" -> sendState = MqttSendMsgCallback.TIMEOUT
                    "offline" -> sendState = MqttSendMsgCallback.OFFLINE
                }
            }
            LiveEventBus.get(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE).post(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE)
            EventBus.getDefault().post(EVENT_BUS_KEY_RECEIVE_MESSAGE)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onConnectStateChange(isConnect: Boolean) {
        DataManager.inst.isMqttConnect = isConnect
        mHandler.removeCallbacksAndMessages(null)
        var curSn = MqttManager.getInstance().curSn
        if (isConnect) {
            onCancleLoading()
            val instance = MqttManager.getInstance()

            instance.subscribe(
                    arrayOf(
                            "cmd/up/$curSn",
                            "cmd/back/$curSn/${instance.clientId}"
                    ), intArrayOf(2, 2), object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken) {
                    LiveEventBus.get(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE).post(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE)
                    MqttManager.getInstance().publish(CommmandNum.mStatusRunning, "")
                }

                override fun onFailure(
                        asyncActionToken: IMqttToken,
                        exception: Throwable
                ) {
                    LogUtils.e("onFailure: " + (exception.message))
                    onConnectStateChange(false)
                }
            })
        } else {
            DataManager.inst.isHandOutMessageActivity = false
            DataManager.inst.lastAutoProgram = 0
            Massage7808Armchair.getInstance().tempDeviceStatusBean = null
            LiveEventBus.get(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE).post(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE)
            Activity7808Utils.startHomeActivityClearTop(this)
        }
    }

    open fun publish(func: String?, model: String) {
        publish(func, model, "")
    }

    open fun publish(func: String?, model: String, addition: String?) {
        if (MqttManager.getInstance().isConnect) { //已连接
            showloading()
            MqttManager.getInstance().publish(func, model, addition)
        } else { //未连接
            connectMqtt()
        }
    }

    /**
     * 连接Mqtt
     */

    private fun connectMqtt() {
        LogUtils.e(TAG, "connectMqtt")
        if (MqttManager.getInstance().isConnect) {
            MqttManager.getInstance().disconnect()
        }
        mHandler.postDelayed({
            if (MqttManager.getInstance().connect()) {
                showloading()
                mHandler.postDelayed({
                    cancleloading()
                    ToastUtils.showShort("连接设备服务器失败")
                    MqttManager.getInstance().disconnect()
                }, 30 * 1000)
            }
        }, 500)
    }

}